home *** CD-ROM | disk | FTP | other *** search
/ Tech Arsenal 1 / Tech Arsenal (Arsenal Computer).ISO / tek-01 / 3dkit1.zip / GETOPT.C < prev    next >
Text File  |  1992-05-06  |  2KB  |  75 lines

  1. /* getopt.c  (slightly modified by O.Garcia, 12/4/92) */
  2. /* now it accepts either '-' or '/' as switch character */
  3.  
  4. /*
  5. Newsgroups: mod.std.unix
  6. Subject: public domain AT&T getopt source
  7. Date: 3 Nov 85 19:34:15 GMT
  8.  
  9. Here's something you've all been waiting for:  the AT&T public domain
  10. source for getopt(3).  It is the code which was given out at the 1985
  11. UNIFORUM conference in Dallas.  I obtained it by electronic mail
  12. directly from AT&T.  The people there assure me that it is indeed
  13. in the public domain.
  14. */
  15.  
  16. #include <stdlib.h>
  17. #include <stdio.h>
  18. #include <string.h>
  19.  
  20. #define ERR(s, c)        if(opterr){fprintf(stderr,"%s%s%c\n",argv[0],s,c);}
  21.  
  22. int     opterr = 1;
  23. int     optind = 1;
  24. int     optopt;
  25. char    *optarg;
  26.  
  27. int
  28. getopt(argc, argv, opts)
  29. int     argc;
  30. char    **argv, *opts;
  31. {
  32.         static int sp = 1;
  33.         register int c;
  34.         register char *cp;
  35.  
  36.         if(sp == 1)
  37.                 if(optind >= argc ||
  38.                    (argv[optind][0] != '-' && argv[optind][0] != '/')
  39.                      || argv[optind][1] == '\0')
  40.                         return(EOF);
  41.                 else if(strcmp(argv[optind], "--") == 0 ||
  42.                         strcmp(argv[optind], "//") == 0) {
  43.                         optind++;
  44.                         return(EOF);
  45.                 }
  46.         optopt = c = argv[optind][sp];
  47.         if(c == ':' || (cp=strchr(opts, c)) == NULL) {
  48.                 ERR(": illegal option -- ", c);
  49.                 if(argv[optind][++sp] == '\0') {
  50.                         optind++;
  51.                         sp = 1;
  52.                 }
  53.                 return('?');
  54.         }
  55.         if(*++cp == ':') {
  56.                 if(argv[optind][sp+1] != '\0')
  57.                         optarg = &argv[optind++][sp+1];
  58.                 else if(++optind >= argc) {
  59.                         ERR(": option requires an argument -- ", c);
  60.                         sp = 1;
  61.                         return('?');
  62.                 } else
  63.                         optarg = argv[optind++];
  64.                 sp = 1;
  65.         } else {
  66.                 if(argv[optind][++sp] == '\0') {
  67.                         sp = 1;
  68.                         optind++;
  69.                 }
  70.                 optarg = NULL;
  71.         }
  72.         return(c);
  73. }
  74. 
  75.